<template>
  <el-drawer
    :title="title"
    :visible.sync="visible"
    :size="size"
    :before-close="modelClose"
    :wrapper-closable="false"
  >
    <el-form :ref="refName" label-position="top" :model="model" :rules="rules" class="updateForm">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名:" prop="name">
            <el-input v-model.trim="model.name" :disabled="updateState === 'edit'" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号码:" prop="identityCard">
            <el-input v-model.trim="model.identityCard" :disabled="updateState === 'edit'" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="box-config">
        <div v-for="(configItem, index) in serviceInfoList" :key="index" class="config-item">
          <el-row>
            <el-col :span="12">
              <el-form-item label="服务类型:" required>
                <el-select v-model="configItem.serviceTypeNo" clearable placeholder="请选择" @change="serviceTypeChange($event, index)">
                  <el-option v-for="item in serviceTypeList" :key="item.serviceTypeNo" :label="item.name" :value="item.serviceTypeNo" :disabled="setDisabled(item, index)" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务项目:">
                <el-select v-model="configItem.serviceProjectNos" clearable placeholder="请选择" multiple>
                  <el-checkbox v-model="checked" class="serviceProjectSelectAll" @change="selectAll(configItem)">全选</el-checkbox>
                  <el-option v-for="item in configItem.serviceProjectList" :key="item.serviceProjectNo" :label="item.name" :value="item.serviceProjectNo" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <i class="el-icon-delete" @click="delItem(index)" />
            </el-col>
          </el-row>
          <div v-if="index === serviceInfoList.length - 1" class="btn-add" @click="addItem()"><i class="el-icon-circle-plus" />添加服务</div>
        </div>
      </div>
    </el-form>
    <div class="drawer-footer">
      <div class="drawer-footer-btn">
        <el-button @click="modelClose">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { postAction } from '@/api/manage'
import selectTenant from '@/components/xm/selectTenant'
import { validatorCardId } from '@/utils/validate'
import { api_getServeTypeList, getServeProjectList } from '@/api/serveConfig'
export default {
  components: {
    selectTenant
  },
  props: {},
  data() {
    return {
      model: {},
      refName: 'ruleForm',
      visible: false,
      disableSubmit: false,
      checked: false,
      updateState: '',
      title: '',
      size: '50%',
      serviceInfoList: [],
      serviceTypeList: [],
      serviceProjectList: [],
      rules: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        identityCard: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: validatorCardId, trigger: 'blur' }
        ],
        tenantNo: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },
      url: {
        update: '/service/user/white/config/simultaneous/saveAndEdit'
      }
    }
  },
  computed: {
    setDisabled() {
      return function(opt, index) {
        // 已经选过的服务类型
        const selectedArr = this.serviceInfoList.map(item => item.serviceTypeNo)
        selectedArr.splice(index, 1) // 去掉当前的
        return selectedArr.includes(opt.serviceTypeNo) // 遍历的下拉选项如果 === 已经选过的服务类型, 禁用
      }
    }
  },
  watch: {},
  created() {},
  mounted() {
    this.getServiceType()
  },
  methods: {
    // 添加项
    addItem() {
      this.checked = false
      this.serviceInfoList.push({ serviceTypeNo: '', serviceProjectNos: [], serviceProjectList: [] })
    },
    // 删除项
    delItem(i) {
      this.checked = false
      if (this.serviceInfoList.length <= 1) {
        this.serviceInfoList = [{ serviceTypeNo: '', serviceProjectNos: [], serviceProjectList: [] }]
      } else {
        this.serviceInfoList.splice(i, 1)
      }
    },
    // 获取服务类型
    getServiceType() {
      api_getServeTypeList({ pageNum: 1, pageSize: 200 }).then((res) => {
        if (res.status === 0) {
          this.serviceTypeList = res.data.list || []
          // if (this.serviceTypeList.length) {
          //   this.serviceTypeList = this.serviceTypeList.filter(item => item.name !== '365兜底区半补' && item.name !== '365兜底区全补')
          // }
        }
      })
    },
    // 服务类型change
    serviceTypeChange(no) {
      this.checked = false
      const obj = this.serviceInfoList.find(v => v.serviceTypeNo === no)
      if (obj) {
        obj.serviceProjectList = []
        obj.serviceProjectNos = []
        // 获取服务项目
        getServeProjectList({ pageNum: 1, pageSize: 1000, serviceTypeNo: no }).then((res) => {
          if (res.status === 0) {
            obj.serviceProjectList = res.data.list || []
          }
        })
      }
    },
    add() {
      this.updateState = 'add'
      this.visible = true
      this.model = {}
      this.serviceInfoList = [{ serviceTypeNo: '', serviceProjectNos: [], serviceProjectList: [] }]
      this.$nextTick(() => {
        this.$refs[this.refName]?.clearValidate()
      })
    },
    edit(rowData) {
      this.updateState = 'edit'
      this.$refs[this.refName]?.clearValidate()
      this.visible = true
      console.log('rowData', rowData)
      const arr = [...rowData.simultaneousServiceResps]
      this.getResps(arr)
      this.model = JSON.parse(JSON.stringify(rowData))
      delete this.model.simultaneousServiceResps
    },
    getResps(resps) {
      console.log('resps', resps)
      this.serviceInfoList = resps.map(item => {
      // 处理 serviceType 可能为空的情况
        const serviceTypeNo = item.serviceType ? item.serviceType.serviceTypeNo : ''
        // 处理 serviceProjects 可能为空的情况
        const serviceProjectNos = item.serviceProjects
          ? item.serviceProjects.map(project => project.serviceProjectNo)
          : []
        return {
          serviceTypeNo: serviceTypeNo, // serviceTypeNo，如果 serviceType 为空则赋值为空字符串
          serviceProjectNos: serviceProjectNos, // serviceProjectNos，如果 serviceProjects 为空则赋值为空数组
          serviceProjectList: [] // 默认空数组
        }
      })
      this.serviceInfoList.forEach(item => {
        // 获取服务项目
        getServeProjectList({ pageNum: 1, pageSize: 1000, serviceTypeNo: item.serviceTypeNo }).then((res) => {
          if (res.status === 0) {
            item.serviceProjectList = res.data.list || []
          }
        })
      })
    },
    // 服务项目全选
    selectAll(configItem) {
      if (this.checked) {
        this.$set(configItem, 'serviceProjectNos', configItem.serviceProjectList.map(item => item.serviceProjectNo))
      } else {
        this.$set(configItem, 'serviceProjectNos', [])
      }
    },
    submitForm() {
      console.log('this.model', this.model)
      console.log('this.serviceInfoList', this.serviceInfoList)
      this.model.simultaneousServiceReqList = []
      if (this.serviceInfoList && this.serviceInfoList.length) {
        this.model.simultaneousServiceReqList = this.serviceInfoList.map(v => {
          return {
            serviceTypeNo: v.serviceTypeNo,
            serviceProjectNos: v.serviceProjectNos
          }
        })
      }
      this.$refs[this.refName].validate((valid) => {
        if (valid) {
          this.$store.dispatch('app/setLoading', true)
          postAction(this.url.update, this.model).then((res) => {
            if (res.status === 0) {
              this.modelClose()
              this.$message.success(res.message || '操作成功！')
              this.$emit('ok')
            } else {
              this.$message.warning(res.message || '操作失败！')
            }
          }).finally(() => {
            this.$store.dispatch('app/setLoading', false)
          })
        } else {
          return false
        }
      })
    },
    modelClose() {
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.updateForm{
  padding: 20px 30px 0;
  margin-bottom: 90px;
  ::v-deep .el-form-item__label{
    line-height: 16px;
  }
  .el-select{
    width: 100%;
  }
  .box-config{
    .config-item{
      position: relative;
      margin-bottom: 30px;
      border: 1px solid #d9d9d9;
      padding: 30px;
      .btn-add{
        position: absolute;
        left: 50%;
        bottom: -10px;
        transform: translateX(-50%);
        display: block;
        text-align: center;
        background-color: #fff;
        width: 188px;
        cursor: pointer;
        color: var(--subjectColor);
        .el-icon-circle-plus{
          margin-right: 6px;
          transform: translateY(2px);
          color: var(--subjectColor);
          font-size: 20px;
        }
      }
      .el-icon-delete{
        position: absolute;
        right: -24px;
        bottom: 24px;
        cursor: pointer;
        color: red;
        font-size: 24px;
      }
    }
  }
}
.el-col{
  padding: 0 8px;
}
.drawer-footer{
  position:absolute;
  bottom:0;
  left:0;
  display:flex;
  align-items:center;
  justify-content:flex-end;
  width:100%;
  height:65px;
  background:#fff;
  z-index:999;
  padding: 16px 29px;
  box-shadow: 0px -1px 16px 1px rgba(0,0,0,0.08);
  border-radius: 4px 4px 4px 4px;
  opacity: 1;
}
::v-deep .el-drawer__body {
    overflow: auto;
}
.serviceProjectSelectAll{
  margin: 10px 20px;
}
</style>
